var cartList=[];
var cartCountPriceList=[];
var cartListCookieName = "cart";
var cartTimpStamp = '';
var processing = false;
var skuMaxNum = 99;

var zekou = 1;
var iszeing = 'no';
var voucherId = '';
var voucherDiscount = '';

//提交订单 
function confirmpay(){
	var sale_type = $('#sale_type').val();
	if(sale_type=='advance'){
		var username,mobile,delivery,address,city,area,distributerId,appointment,payment,remark,
			voucherId,orderid,custprice,presell,pay_int,orderId,delivery,distributerId;
		username =!isNull($('#username').val()) ? Trim($('#username').val(),'g') : '';
		mobile   =!isNull($('#mobile').val()) ?  Trim($('#mobile').val(),'g') : '';
		address =!isNull($('#presaleAddress').val()) ?  Trim($('#presaleAddress').val(),'g') : '';
		remark   =!isNull($('#remark').val()) ?  Trim($('#remark').val(),'g') : '';
		// appointment = $('input[name=svtime]').val();
		appointment ='1111-11-11';
		voucherId = $('#voucherId').val();
		payment   = $('#payment').val();
		orderId = $('#orderid').val();
		custprice = $('#custprice').val();
		presell = $('#presell').val();
		distributerId=0;
		if(iszeing=='no'){
			presell = 0;
		}if(iszeing=='yes'){
			presell = (($('#total_cart').text() - $('#dikou').text() - $('#zhekou').text())*0.05).toFixed(2);
		}
		delivery = 2;//配送上门
		pay_int = $('#pay_int').val();
		var reg = /^0?1[3|4|5|6|7|8][0-9]\d{8}$/;
		if(!username){
			alert('请选择收货地址');
			return false;
		}else if((!reg.test(mobile)&&(mobile.length!=11))){
			alert('收货人手机格式不对，请重新选择收货地址');
			return false;
		}else if(!address){
			alert('请选择收货地址');
			return false;
		}else if(isNull(pay_int)){
			alert('请选择支付方式');
			return false;
		}else{
			$('#confirm_pay').attr("disabled","true");
			$.ajax({
				type: "post",
				url : "/order/complete",
				dataType:'json',
				data:{'id':orderId,'username':username,'mobile':mobile,'address':address,'remark':remark,'delivery':delivery,'payment':payment,'appointment':appointment,'voucherId':voucherId,'presell_discount':presell,'pay_int':pay_int,'distributerId':distributerId,'type':sale_type},
				success: function(info){
					var msg = info.msg;
					if(msg=='gotologin'){
						var rurl = '/';
						location.href="/login?rurl="+rurl;
						return false;
					}else if(msg=='toSuccess'){
						location.href='/order/success?oid='+orderId;
						return false;
					}else if(msg=='distributerClosed'){
						alert('参数错误');
						return false;
					}else if(msg=="hasPaid"){
						location.href = '/order/list';
						return false;
					}else if(msg==1){
						var oid = info.oid;
						var payment = info.payment;
						var pay_int = info.pay_int;

						if (getCookie('cartCountPrice')) {
							cartCountPriceList=[];
							clearCookie('cartCountPrice');
							setCookie('tab','home');
						}
						if(parseInt(payment) == 2 && parseInt(pay_int) == 2 ){
							callWXPay(oid);
						}else if(parseInt(payment) == 2 && parseInt(pay_int) == 3){
							var transactionId = info.transactionId;
							var inserttime = info.inserttime;
							if(transactionId==0){
								alert('支付失败，订单已支付或订单已超过支付期限');
								location.href="/order/status?oid="+oid;
							}else{
								location.href = "/order/zfbpay?oid="+oid+"&transactionId="+transactionId+"&inserttime="+inserttime;
							}
						}else if(parseInt(payment) == 2 && parseInt(pay_int) == 4){
							location.href="/personal/topuppay?oid="+oid;
						}else{
							location.href="/order/success?oid="+oid;
						}
					}else{
						$('.error_msg').html('提交失败,请重新下单');
					}
				},
				complete: function () {

					$('#confirm_pay').attr("disabled","false");
				}
			});
		}
	}else{
		var username = Trim($('#username').val(),'g');
		var mobile = Trim($('#mobile').val(),'g');
		var delivery = $('.delivery').attr('tig');
		var address = '';
		var distributerId = '';
		if(delivery==1){
			address=Trim($('#zitiName').text()+$('#zitiAddress').text(),'g');
			distributerId = $('#zitiName').attr('distributerId');
		}else{
			address = Trim($('#address_songhuo').val(),'g');
		}
		if(isNull(address)){
			alert('收货地址为空！');
			return false;
		}
		var appointment = '';
		if($('.timetoday').length>0 && $('.timetoday').css('display')=='block'){
			appointment =  $('#appointmenttoday').val();
		}
		if($('.timetomorrow').length>0 &&$('.timetomorrow').css('display')=='block'){
			appointment =  $('#appointmenttomorrow').val();
		}
		if($('.timeaftertomorrow').length>0 &&$('.timeaftertomorrow').css('display')=='block'){
			appointment =  $('#appointmentaftertomorrow').val();
		}
		var payment = $('#payment').val();
		var remark = $('#remark').val();

		var voucherId = $('#voucherId').val();
		var orderid = $('#orderid').val();

		var custprice = $('#custprice').val();
		var presell = $('#presell').val();
		if(iszeing=='no'){
			presell = 0;
		}if(iszeing=='yes'){
			presell = (($('#total_cart').text() - $('#dikou').text() - $('#zhekou').text())*0.05).toFixed(2);
		}
		var pay_int = $('#pay_int').val();
		// alert('delivery='+delivery+'*****address='+address+'@distributerId='+distributerId+'@appointment='+appointment+'@payment='+payment+'@pay_int='+pay_int);return false;
		if(isNull(username)){
			$('.error_msg').html('亲，请填写收货人');
			return false;
		}
		if(isNull(mobile)){
			$('.error_msg').html('亲，请填写收货人电话');
			return false;
		}
		if(mobile.length==0)
		{
			$('.error_msg').html('请输入手机号码！');
			return false;
		}
		if(mobile.length!=11)
		{
			$('.error_msg').html('请输入有效的手机号码！');
			return false;
		}

		var myreg = /^1[3|4|5|7|8][0-9]\d{4,8}$/;
		if(!myreg.test(mobile))
		{
			$('.error_msg').html('请输入有效的手机号码！');
			return false;
		}
		if(isNull(address)){
			$('.error_msg').html('亲，请填写收货人地址');
			return false;
		}if(isNull(appointment)){
			$('.error_msg').html('亲，请填写预约时间');
			return false;
		}
		if(isNull(pay_int)){
			$('.error_msg').html('亲，请选择支付方式');
			return false;
		}
		$('#confirm_pay').attr("disabled","true");
		$.ajax({
			type: "post",
			url : "/order/complete",
			dataType:'json',
			data:{'id':orderid,'username':username,'mobile':mobile,'address':address,'remark':remark,'delivery':delivery,'payment':payment,'appointment':appointment,'voucherId':voucherId,'presell_discount':presell,'pay_int':pay_int,'distributerId':distributerId},
			success: function(info){
				var msg = info.msg;
				if(msg=='gotologin'){
					var rurl = '/';
					location.href="/login?rurl="+rurl;
					return false;
				}
				if(msg=='toSuccess'){
						location.href='/order/success?oid='+orderid;
						return false;
				}
				if(msg=='distributerClosed'){
					alert('自提点已关闭，请返回首页重新选择自提点');
					setCookie('tab','home');
					location.href='/';
					return false;
				}
				if(msg=="hasPaid"){
					location.href = '/order/list';
					return false;
				}
				if(msg==1){
					var oid = info.oid;
					var payment = info.payment;
					var pay_int = info.pay_int;

					if (getCookie('cartCountPrice')) {
						cartCountPriceList=[];
						clearCookie('cartCountPrice');
						setCookie('tab','home');
					}
					if(parseInt(payment) == 2 && parseInt(pay_int) == 2 ){
						callWXPay(oid);
					}else if(parseInt(payment) == 2 && parseInt(pay_int) == 3){
						var transactionId = info.transactionId;
						var inserttime = info.inserttime;
						if(transactionId==0){
							alert('支付失败，订单已支付或订单已超过支付期限');
							location.href="/order/status?oid="+oid;
						}else{
							location.href = "/order/zfbpay?oid="+oid+"&transactionId="+transactionId+"&inserttime="+inserttime;
						}
					}else if(parseInt(payment) == 2 && parseInt(pay_int) == 4){
						location.href="/personal/topuppay?oid="+oid;
					}else{
						location.href="/order/success?oid="+oid;
					}

				}else{
					$('.error_msg').html('提交失败,请重新下单');
				}
			},
			complete: function () {

				$('#confirm_pay').attr("disabled","false");
			}
		});
	}
}

//delivery
function deliveryHelper(el){
	var tig = $(el).attr('tig');
	if(tig == '1'){
		$('#ziti_add').show();
		$('#shangmen_add').hide();
	}else{
		$('#ziti_add').hide();
		$('#shangmen_add').show();
	}
	$('.deliveryMethod').html('<img src="/images/meigou.png"  class="gougou">');
	$('#deliveryMethod'+tig).html('<img src="/images/yigou.png"  class="gougou">');
	$('#delivery').val(tig);
}

function gotopay()
{
	var oid = $('#orderid').val();
	var inserttime = $('#inserttime').val();
	var hid_method = $('#hid_method').val();
	if(hid_method==2){
		callWXPay(oid);
	}else if (hid_method==3){
		location.href="/personal/topuppay?oid="+oid;
	}else{
		$.ajax({
		  type: "post", 
		  url : "/order/pay", 
		  dataType: 'json',
		  data: {'oid':oid},
		  success: function(info){
			var msg = info.msg;
			if(msg=='success'){
				var transactionId = info.transactionId;
				if(transactionId==0){
					alert('支付失败，订单已支付或订单已超过支付期限');
					location.href="/order/status?oid="+oid;
				}else{
					location.href='/order/zfbpay?oid='+oid+'&transactionId='+transactionId+'&inserttime='+inserttime;
				}
			}
			if(msg=='error'){
				alert('支付失败，订单已支付或订单已超过支付期限');
				location.href="/order/status?oid="+oid;
			}
		  }
		});
	}
}
//wxpay
function callWXPay(oid)
{
	$.ajax({
		  type: "post", 
		  url : "/order/wxpay", 
		  dataType: 'json',
		  data: {'oid':oid},
		  success: function(info){
			var msg = info.msg;
			if(msg=='errorToSite'){
				location.href = '/';
			}else if(msg=='errorToOrderList'){
				location.href = '/order/list'
			}else if (msg == 'errorToLogin'){
				var rurl = '/order/list';
				location.href = '/login?rurl='+rurl;
			}else if(msg=='success'){
				var wxparams = info.wxparams;
				var userid = info.uid;
				var orderid = info.orderid;
				var transactionId = info.transactionId;
			
				if (typeof WeixinJSBridge == "undefined"){
					if( document.addEventListener ){
						document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
					}else if (document.attachEvent){
						document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
						document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
					}
				}else{
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest',
						wxparams,
						function(res){
							WeixinJSBridge.log(res.err_msg);
							if(res.err_msg=="get_brand_wcpay_request:fail"){
								alert('支付失败，订单已支付或订单已超过支付期限');
								location.href="/order/status?oid="+orderid;
							}if (res.err_msg=="get_brand_wcpay_request:cancel"){
								alert('支付取消');
								location.href="/order/status?oid="+orderid;
							}if(res.err_msg=="get_brand_wcpay_request:ok"){
								location.href="/order/wxquery?oid="+orderid+"&trade_no="+transactionId+"&type=kk";
							}
						}
					);
				}
			}else{
				location.href = '/error';
			}
			
		  }
	});
	
}

//商家详情
function custDetailHelper(el){
	$('.cust_tab td').removeClass('cust_menu');
	$(el).addClass('cust_menu');
	if($(el).attr('tig')=='1'){
		$('.pingjia').show();
		$('.xiangqing').hide();
		$('.huodong').hide();
	}
	if($(el).attr('tig')=='2'){
		$('.pingjia').hide();
		$('.xiangqing').show();
		$('.huodong').hide();
	}
	if($(el).attr('tig')=='3'){
		$('.pingjia').hide();
		$('.xiangqing').hide();
		$('.huodong').show();
	}
}





function position(){
	$("body").append("<div id='masktg'></div>");
    $("#masktg").addClass("mask").fadeIn("slow");
    $("#position_msg").fadeIn("slow");
	setInterval(function(){
		changeDian();
	},1000);
	setTimeout(function(){
		get_location();
	},2000);
}
//切换地址
function get_location(){
	if(navigator.geolocation){
		navigator.geolocation.getCurrentPosition(show_map,handle_error,{enableHighAccuracy:true,maximumAge:1000,timeout:8000});
	}else{
		alert("您的微信浏览器不支持定位");
	}
}

function fadeout_div(){
     $("#masktg").fadeOut("fast");
     $("#position_msg").fadeOut("fast");
}

function changeDian(){
    if($("#dian").css('display')=='none'){
        $("#dian").show();
    }else{
        $("#dian").hide();
    }
}

function handle_error(err){
	fadeout_div();
	switch(err.code){
		case 1:
			alert("位置服务被拒绝");
			break;
		case 2:
			alert("暂时获取不到位置信息");
			break;
		case 3:
			alert("获取信息超时");
			break;
		default:
			alert("定位失败，请手动输入");
			break;
	}
}

function show_map(position){
	var latitude = position.coords.latitude;
	var longitude = position.coords.longitude;
	$.ajax({
		  type: "post", 
		  url : "/address", 
		  dataType: 'json',
		  data: {'lat':latitude,'lon':longitude},
		  success: function(info){
			var list = info.msg;
			var len = list.length;
			if(len>0 && list!='noData'){
				$('#lenLocation').val(len);
				$('#position_list').html('');
				$('#position_list').append('<div class="search_ziti">定位附近小区列表</div>');
				for(var i=0;i<len;i++){
					var domainId = list[i].id;
					var domainName = list[i].domainname;
					var address = list[i].address;
					$('#position_list').append('<a href="javascript:void(0);" onclick="javascript:domainOnClick(this);return false;" domainId="'+domainId+'" domainName="'+domainName+'" domainAdd ="'+address+'"><div class="address_list">'+domainName+'<br><span>'+address+'</span></div></a>');
				}
				$('#searchRes').hide();
				$('.history').hide();
				$('.html_bg').hide();
			}else{
				$('#position_list').html('');
				$('#position_list').append('<div class="search_ziti">您附近小区暂未开通</div>');
			}
			fadeout_div();
		  }
	});
}


var domainList = [];
function loadDomain(){

	var cook = getCookie("domain");
	if (isNull(cook))
	 return;
	if(cook.length > 0){
      tmp = cook.split(",");
	  var row = tmp.length/3;
	  for(var i = 0; i < row; i++){
		var one =[];
		for(var j=0; j<3; j++){
		  one.push(tmp[3*i+j]);
		}
		domainList.push(one);
	  }//转成数组
	  $('.history').append('<div id="history" class="my_address">历史记录</div><div class="history_list"></div>');
	  for(var n=0;n<domainList.length;n++){
		if(n<5){
		$(".history_list").append('<a href="javascript:void(0);"  onclick="javascript:domainOnClick(this);return false;" domainId = "'+domainList[n][0]+'" domainName="'+domainList[n][1]+'" domainAdd="'+domainList[n][2]+'"><div class="address_list">'+domainList[n][1]+'<br><span>'+domainList[n][2]+'</span></div>');
		}
	  }
	}
}
//点击小区
function domainOnClick(el){
	var domainId = $(el).attr('domainId');
	var domainName = $(el).attr('domainName');
	var domainAddress = $(el).attr('domainAdd');
	var one = [];
	one.push(domainId);
	one.push(domainName);
	one.push(domainAddress);
	var isRepeat=false;
	for(var i=0;i<domainList.length;i++){
		if(domainList[i][0]==domainId){
			isRepeat = true;
		}
	}
	if(!isRepeat)
	domainList.unshift(one); 
	setCookie('domain',domainList);
	
	$.ajax({
		  type: "post", 
		  url : "/address", 
		  dataType: 'json',
		  data: {'domainId':domainId,'domainName':domainName,'domainAddress':domainAddress,'tag':'domainClick'},
		  success: function(info){
			var res = info.msg;
			if(res=='toAddress'){
				location.href="/address";
			}else{
				location.href="/";
			}
		  }
	});
	
	
}

function isNull(arg1)
{
  return !arg1 && arg1!==0 && typeof arg1!=="boolean"?true:false;
}

function goTo(title, URL) {
	history.replaceState({},title, URL);
}

//读取cookies
function getCookie(name) 
{ 
  var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
  if(arr=document.cookie.match(reg))
	return unescape(arr[2]); 
  else 
    return null; 
}

//写cookies 
function setCookie(name,value) 
{ 
  var Days = 1; 
  var exp = new Date(); 
  exp.setTime(exp.getTime() + Days*24*60*60*1000); 
  document.cookie = name + "="+ escape (value) + ";path=/;expires=" + exp.toGMTString(); 
} 
//清除cookie  
function clearCookie(name) {  
    setCookie(name, "", -1);  
} 

function saveCartList() {
  setCookie(cartListCookieName,cartList);
  //alert(cartList);
}

function resetCartList() {
  if (getCookie('cartCountPrice')) {
    cartCountPriceList=[];
    clearCookie('cartCountPrice');
    resetLayout();
    window.location.href=window.location.href;
  }
}
function amountIsGreatThan99(){
  var cook = getCookie('cartCountPrice');
  var cartCountPriceList = cookToArr(cook);
  if (isNull(cartCountPriceList)) {
    return false;
  } else {
    var amount = 0;
    for(var i=0; i<cartCountPriceList.length; i++){
      var skuAmount = parseInt(cartCountPriceList[i][3]);
	  if (skuAmount > 0) {
		amount ++;
	  }
    }
	if(amount>=skuMaxNum){
		return true;
	}
	return false;
  }
}
function updateLayout(custId) {
  if (cartCountPriceList.length == 0) {
    resetLayout();
  } else {
    var amount = 0;
    var total = 0;
    for(var i=0; i<cartCountPriceList.length; i++){
      var skuId = cartCountPriceList[i][1];
      var skuAmount = parseInt(cartCountPriceList[i][3]);
      var skuPrice = parseFloat(cartCountPriceList[i][2]);
      var id = "sku-"+skuId+"-"+custId;
      var cartId = "cart-sku-"+skuId+"-"+custId;
      var el = $("#"+id);
      if (el) {
      	el.html(skuAmount);
      }
	  el = $("#"+cartId);
	  if (el) {
        el.html(skuAmount);
      }
      total = parseFloat(total) + skuAmount * skuPrice;
      total = total.toFixed(2);
	  if (skuAmount > 0) {
		amount ++;
	  }
    }
	$('#cart_num').html(amount);
  }
}

//购物车更新页面
function updateCartLayout(){
	var cook = getCookie('cartCountPrice');
	var cartCountPriceList = cookToArr(cook);
	var newCartList = [];
    var amount = 0;
    var total = 0;
    var priceChanged = false;
    var priceList = "温馨提示：\n\n";
    for(var i=0; i<cartCountPriceList.length; i++){
      var skuId = cartCountPriceList[i][1];
      var skuAmount = parseInt(cartCountPriceList[i][3]);
      var skuPrice = parseFloat(cartCountPriceList[i][2]);
	  var custId = cartCountPriceList[i][0];
      var cartId = "cart-sku-"+skuId+"-"+custId;
	  el = $("#"+cartId);
	  if (el) {
        el.html(skuAmount);
      }
	  var currentSkuPrice = el.attr('skuprice');
	  if(el.attr('isdel')==0){
		  if(currentSkuPrice!=skuPrice){
			  var nameSku = $('#name'+skuId);
			  priceChanged = true;
			  priceList += nameSku.html()+"，原价"+skuPrice+"元，现价"+currentSkuPrice+"元\n\n";
			  cartCountPriceList[i][2]=currentSkuPrice;
			  setCookie('cartCountPrice',cartCountPriceList);
		  }
		  newCartList.push(cartCountPriceList[i]);
		  total = parseFloat(total) + skuAmount * currentSkuPrice;
		  total = total.toFixed(2);
		  if (skuAmount > 0) {
			amount ++;
		  }
	
	  }
    }
    if (priceChanged == true) {
	  alert(priceList);	  
	}
	setCookie('cartCountPrice',newCartList);
	$('#cart_num').html(amount);
	$('#cart_total').html(total);
	
	var mindelever = parseFloat($('#mindeliver').val());
	var cha_money = parseFloat($('.cha_money').html());
	if(total>=mindelever){
		$('.goto').html('<a class="shopping_carta" href="javascript:void(0);" id="what_tg" onclick="javascript:toJieSuan();return false;">去结算</a>');
	}else{
		$('.goto').html('<span class="cha">差<span class="cha_money"><?php echo '
		+'$this->client_row[0]["mindeliver"];?></span>元起订</span>');
		var cha = parseFloat(mindelever-total);
		var cha_2 = Math.round(cha*100)/100;
		$('.cha_money').html(cha_2);
	}
}

//详情页添加
function detailAdd(){
	
	var cook = getCookie('cartCountPrice');
	var cartCountPriceList = [];
	
	var el = $('#detailMinus');
	var skuId = el.attr('skuId');
	var custId = el.attr('custId');
	var onsale = el.attr("skuOnsale");
	var saleAmount = el.attr('skuSaleAmount');
	var one=[];
	one.push(custId);
	one.push(skuId);
	one.push(el.attr("skuPrice"));
	one.push(1);
	if(isNull(cook)){
		$('#detail-'+skuId).html(1);
		cartCountPriceList.push(one);
	}else{
		  cartCountPriceList = cookToArr(cook);
		  var position = -1;
		  for(var i=0; i<cartCountPriceList.length; i++){
			var cart_sku_id = cartCountPriceList[i][1];
			var cart_cust_id = cartCountPriceList[i][0];
			if (cart_sku_id == skuId) {
				position = i;
				break;
			}
		  }
		
		if (position >= 0) {
			if(onsale==1&&cartCountPriceList[position][3]==saleAmount){
				alert('本促销商品每单限购'+saleAmount+'份，亲');
				return;
			}
			if(cartCountPriceList[position][3]>=skuMaxNum){
				alert('单品限购99份');
				return;
			}
			one[3] = parseInt(cartCountPriceList[position][3]) + 1;
			$('#detail-'+skuId).html(one[3]);
			cartCountPriceList[position] = one; 
		}else{
			if(amountIsGreatThan99()==true){
			  alert('购物车已塞满');
			  return false;
			}
			$('#detail-'+skuId).html(1);
			cartCountPriceList.push(one);
		}
	}
    setCookie('cartCountPrice',cartCountPriceList);
	loadCookieDetails();
}
//详情页移除
function detailMinus(){
	var cook = getCookie('cartCountPrice');
	var cartCountPriceList = [];
	
	var el = $('#detailMinus');
	var skuId = el.attr('skuId');
	var custId = el.attr('custId');
	
	if(!isNull(cook)){
		cartCountPriceList = cookToArr(cook);
		var position = -1;
		for(var i=0; i<cartCountPriceList.length; i++){
			var cart_sku_id = cartCountPriceList[i][1];
			var cart_cust_id = cartCountPriceList[i][0];
			//TODO, logic problem
			if (cart_sku_id == skuId && cart_cust_id == custId) {
				position = i;
				break;
			} else if (cart_sku_id == skuId) {
				position = i;
				break;
			}
		}
		if (position >= 0) {
			var amount = parseInt(cartCountPriceList[position][3]) - 1;
			cartCountPriceList[position][3] = amount;
			$('#detail-'+skuId).html(amount);
			if (amount < 1){
				$('.detailCart').html(0);
				$('#detail-'+skuId).html(0);
				cartCountPriceList.splice(position,1);
			}
			setCookie('cartCountPrice',cartCountPriceList);
		}
		loadCookieDetails();
	}
}
//添加
function addOneItem (custId, skuId) {
  
  var el = $('#pro-'+skuId+'-'+custId);
  if (isNull(el.attr("skuName"))) {
    return;
  }
  
  var onsale = el.attr("skuOnsale");
  var saleAmount = el.attr('skuSaleAmount');
  var oneCartPrice = [];
  oneCartPrice.push(custId);
  oneCartPrice.push(skuId);
  oneCartPrice.push(el.attr("skuPrice"));
  oneCartPrice.push(1);
  var pos = -1;
  for(var j=0;j<cartCountPriceList.length;j++){
	  var cartSkuId=cartCountPriceList[j][1];
	  if(cartSkuId == skuId){
		  pos=j;
		  break;
	  }
  }
  if (pos >= 0) {
	if(onsale==1&&cartCountPriceList[pos][3]==saleAmount){
		alert('本促销商品每单限购'+saleAmount+'份，亲');
		return;
	}
	if(cartCountPriceList[pos][3]>=skuMaxNum){
		alert('单品限购99份');
		return;
	}
    oneCartPrice[3] = parseInt(cartCountPriceList[pos][3]) + 1;
  	cartCountPriceList[pos] = oneCartPrice; 
  } else {
	if(amountIsGreatThan99()==true){
		alert('购物车已塞满');
		return false;
	}
	cartCountPriceList.push(oneCartPrice);
  }
	updateLayout(custId);
	setCookie('cartCountPrice',cartCountPriceList);
}

//移除
function removeOneItem(custId, skuId) {
  var pos = -1;
  for(var j=0;j<cartCountPriceList.length;j++){
	var cartSkuId = cartCountPriceList[j][1];
	var cartCustId = cartCountPriceList[j][0];
	if(cartSkuId == skuId && cartCustId == custId){
	  pos = j;
	  break;
	}else if(cartSkuId == skuId){
		pos = j;
		break;
	}
  }
  if (pos >= 0) {
	var amount = parseInt(cartCountPriceList[pos][3]) - 1;
    cartCountPriceList[pos][3] = amount;
	updateLayout(custId);
	if (amount < 1){
		cartCountPriceList.splice(pos,1);
	}
    setCookie('cartCountPrice',cartCountPriceList);
  }
}

function resetLayout() {
  $('.request-amount').html(0);
  $('#cart_num').html(0);
  $('#cart_total').html(0);
}
function closeCart(){
	$('#what_tgbox').css('display','none');
 	$("#masktg").css({ 'display': 'none' });
}
  
function init_cart_btns() {
  //添加
  $(".add").click(function(){//计算改变数量和price;setCookie
	var skuId = $(this).attr("skuId");
  	var custId = $(this).attr("custId");
	addOneItem(custId, skuId);
  });
  
  //移除
  $(".minus").click(function(){
  	var skuId = $(this).attr("skuId");
  	var custId = $(this).attr("custId");
    removeOneItem(custId, skuId);
  });
 
  //清空购物车
  $('.clear_cart').click(function(){
		resetCartList();
  });

  //关闭购物车
  $('#closeBtn').click(function(){
  	$('#shoppingCart').css('display','none');
  	$("#masktg").css({ display: 'none' });
  });
}

//清空购物车
function clearCart(){
	var r=confirm("确定清空购物车吗？");
	if (r==true){
		if(getCookie('cartCountPrice')){
			cartCountPriceList = [];
			clearCookie('cartCountPrice');
			setCookie('tab','category');
			location.href="/";
		}
	}else{
	}
}
//tabs color
function loadTabsColor(){
		var tab = getCookie('tab');
		if (tab == 'home') {
			$('#homePage').html('<img src="/images/homeGreen.png">');
		} else if (tab == 'category') {
			$('#categoryPage').html('<img src="/images/categoryGreen.png">');
		} else if (tab == 'personal') {
			$('#personalPage').html('<img src="/images/personalGreen.png">');
		}
	}
//去结算
 function toJieSuan(){
	if (Date.parse(new Date()) - cartTimpStamp > 300000) {
		location.href = location.href;
		return;
	}
  	var custid=$('#custid').val();
  	var shopid=$('#shopid').val();
	var etime = $('#etime').val();
	var stime = $('#stime').val();
	var cook = getCookie('cartCountPrice');
	var cartList = cookToArr(cook);
	var postBody = "list="+cartList+"&custid="+custid+"&shopid="+shopid+"&etime="+etime+"&stime="+stime;
	$.ajax({
		  type: "post",
		  url : "/sku",
		  dataType: 'text',
		  data: postBody,
		  success: function(info){
				if(info=='error'){
					alert('结算失败');
					return;
				}
				if(info=='distributerClosed'){
					alert('自提点已关闭，请返回首页重新选择自提点');
				}
				if(info==0){
					location.href="/login";
				}
				if(info>0){
					location.href="/order/complete?oid="+info;
				}
		  }
	});
 }
 function cookToArr(cook){
	var cartCountPriceList = [];
	if (isNull(cook))
		return;
	if(cook.length > 0){
		tmp = cook.split(",");
		var row = tmp.length/4;
		for(var i = 0; i < row; i++){
			var one =[];
			for(var j=0; j<4; j++){
				one.push(tmp[4*i+j]);
			}
			cartCountPriceList.push(one);
		}//转成数组
	}
	return cartCountPriceList;
}
function cookToArray(cook){
	var cartList = [];
	if (isNull(cook))
		return;
	if(cook.length > 0){
		tmp = cook.split(",");
		var row = tmp.length/8;
		for(var i = 0; i < row; i++){
			var one =[];
			for(var j=0; j<8; j++){
				one.push(tmp[8*i+j]);
			}
			cartList.push(one);
		}//转成数组
	}
	return cartList;
}

 //点击购物车中的添加
 function add_cart(el){
  	var skuId = $(el).attr("skuId");
  	var custId = $(el).attr("custId");
	
  	var cook = getCookie('cartCountPrice');
	var cartCountPriceList = cookToArr(cook);
	
	var position = -1;
	for(var i=0; i<cartCountPriceList.length; i++){
		var cart_sku_id = cartCountPriceList[i][1];
		var cart_cust_id = cartCountPriceList[i][0];
		if (cart_sku_id == skuId) {
			position = i;
			break;
		}
	}
  if (position >= 0) {
	var onsale =$(el).attr('onsale');
	var saleAmount = $(el).attr('saleAmount');
	if(onsale==1&&cartCountPriceList[position][3]==saleAmount){
		alert('本促销商品每单限购'+saleAmount+'份，亲');
		return;		
	}
	if(cartCountPriceList[position][3]>=skuMaxNum){
		alert('单品限购99份');
		return;
	}
	cartCountPriceList[position][3] = parseInt(cartCountPriceList[position][3]) + 1;
  }  
	setCookie('cartCountPrice',cartCountPriceList);
	updateCartLayout();
  }
  //点击购物车中的移除
function minus_cart(el){
  	var skuId = $(el).attr("skuId");
	var custId = $(el).attr("custId");
	
  	var cook = getCookie('cartCountPrice');
	var cartCountPriceList = cookToArr(cook);
	 var position = -1;
  for(var i=0; i<cartCountPriceList.length; i++){
  	var cart_sku_id = cartCountPriceList[i][1];
  	var cart_cust_id = cartCountPriceList[i][0];
	//TODO, logic problem
  	if (cart_sku_id == skuId && cart_cust_id == custId) {
  		position = i;
  		break;
  	} else if (cart_sku_id == skuId) {
	  	position = i;
		break;
	}
  }

  if (position >= 0) {
	var amount = parseInt(cartCountPriceList[position][3]) - 1;
    cartCountPriceList[position][3] = amount;
	if (amount < 1){
		var el = $('#pro'+skuId+'-'+custId);
		el.hide();
		cartCountPriceList.splice(position,1);
		if(cartCountPriceList.length<1){
			setCookie('tab','category');
			location.href="/";
		}
	}
	setCookie('cartCountPrice',cartCountPriceList);
	updateCartLayout();
  }
  }
function edit_address(){
	var username = $('#username').val();
	var mobile = $('#mobile').val();
	$("#address_view").html('<div id="address_edit"><div class="cp_name">姓名<span><input  class="cp_form_input" id="username" type="text" value="'+username+'" name="username" placeholder="收货人姓名"></span></div><div class="cp_name">手机<span><input  class="cp_form_input" id="mobile" type="text" value="'+mobile+'" name="phone" placeholder="收货人电话号码"></span></div></div>');
}
//初始化 预约折扣的
function init_iszeing(){
	iszeing = $('#iszeing').val();
}

//修改价格
function updatePrice (id, discount, ze) {
	if (id > 0 && discount > 0) {
		$('#hongbao_money').html(discount+'元');
		$('#dikou').html(discount);
		$('#voucherId').val(id);
		var leftpay = (($('#total_cart').text() - $('#dikou').text() - $('#zhekou').text())*ze).toFixed(2);
		if(leftpay<0){
			leftpay = 0;
		}
		$('#leftpay').html(leftpay);
		// $('#hb_holder').attr('style','display:auto');
	} else {
		$('#hongbao_money').html('>');
		$('#dikou').html(0);
		$('#voucherId').val(0);
		var leftpay = (($('#total_cart').text() - $('#dikou').text() - $('#zhekou').text())*ze).toFixed(2);
		if(leftpay<0){
			leftpay = 0;
		}
		$('#leftpay').html(leftpay);
		// $('#hb_holder').attr('style','display:none');
	}
}


//明天收货
function shouhuo_time(){
	$('#shou_tomorrow').html('<img src="/images/yigou.png"  class="gougou">');
	$('#shou_today').html('<img src="/images/meigou.png"  class="gougou">');
	$('#tom_tod').val('1');
	$('#tomorrow').show();
	$('#today').hide();
	var end_time = $('#iszeing').attr('time-limit');
	if(MyTimeDaNow(end_time)){
		if($('#yuyue_notice').length>0){
			yuyue_youhui();
		}else{
			stop_yuyue_youhui();
		}
	}else{
		stop_yuyue_youhui();
	}
}
//预约无折扣
function stop_yuyue_youhui(){
  $('#youhui').hide();
  iszeing = 'no';
  var pay_int = $('#pay_int').val();
  if(pay_int==2 || pay_int==3){
  	updatePrice(voucherId,voucherDiscount,1);
  }else{
  	updatePrice(0,0,1);
  }
  $('#presell').val(0);
}
//预约有折扣
function yuyue_youhui(){
  $('#youhui').show();
  iszeing = 'yes';
  var pay_int = $('#pay_int').val();
  if(pay_int==2 || pay_int==3){
  	updatePrice(voucherId,voucherDiscount,zekou);
  }else{
  	updatePrice(0,0,zekou);
  }
}

function message_end_time(){
	var len = $('.today_time').length;
	if($('#today').css('display')!='none'){
		if(len == 0){
		alert("亲，今天的营业时间已经结束，预约明天的吧");
		return false;
		}
	}
}
//今日收货
function shouhuo_time_today(){
	//message_end_time();
	$('#shou_tomorrow').html('<img src="/images/meigou.png"  class="gougou">');
	$('#shou_today').html('<img src="/images/yigou.png"  class="gougou">');
	$('#tom_tod').val('2');
	$('#tomorrow').hide();
	$('#today').show();
	$('#leftpay').text($('#total_cart').text());
	$('#youhui').hide();
	$('#presell').val(0);
	iszeing = 'no';
	var pay_int = $('#pay_int').val();
	if(pay_int==2 || pay_int==3){
			updatePrice(voucherId,voucherDiscount,1);
	}else{
			updatePrice(0,0,1);
	}
}

function zhfu_yue(){
	$('#yue_zhifu').html('<img src="/images/yigou.png"  class="gougou">');
	$('#weixin_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
	$('#zhifubao_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
	$('#huodao_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
	$('#payment').val('2');
	$('#pay_int').val('4');
	$('#user_voucher').show();
	if(iszeing=='yes'){
		updatePrice(voucherId,voucherDiscount,zekou);
	}else{
		updatePrice(voucherId,voucherDiscount,1);
	}
}
function zhfu_weixin(){
	$('#weixin_zhifu').html('<img src="/images/yigou.png"  class="gougou">');
	$('#zhifubao_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
	$('#yue_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
	$('#huodao_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
	$('#payment').val('2');
	$('#pay_int').val('2');
	$('#user_voucher').show();
	if(iszeing=='yes'){
		updatePrice(voucherId,voucherDiscount,zekou);
	}else{
		updatePrice(voucherId,voucherDiscount,1);
	}
}

function zhfu_taobao(){
	$('#weixin_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
	$('#yue_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
	$('#zhifubao_zhifu').html('<img src="/images/yigou.png"  class="gougou">');
	$('#huodao_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
	$('#payment').val('2');
	$('#pay_int').val('3');
	$('#user_voucher').show();
	if(iszeing=='yes'){
		updatePrice(voucherId,voucherDiscount,zekou);
	}else{
		updatePrice(voucherId,voucherDiscount,1);
	}
}


function zhfu_dao(){
	$('#weixin_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
	$('#zhifubao_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
	$('#huodao_zhifu').html('<img src="/images/yigou.png"  class="gougou">');
	$('#payment').val('1');
	$('#pay_int').val('1');
	$('#user_voucher').hide();
	if(iszeing=='yes'){
		updatePrice(0,0,zekou);
	}else{
		updatePrice(0,0,1);
	}
	$('.xiala').hide();
}

//load carList
function loadCookie(custId) {
	cartCountPriceList = [];
	var cookCart = getCookie('cartCountPrice');
	if (isNull(cookCart))
    return;
	if(cookCart.length > 0){
		tmp = cookCart.split(",");
		var row = tmp.length/4;
		for(var i = 0; i < row; i++){
		   var one =[];
		   for(var j=0; j<4; j++){
			one.push(tmp[4*i+j]);
		   }
		   cartCountPriceList.push(one);
		}//转成数组
		updateLayout(custId);
	}
}
//详情页loadCookie
function loadCookieDetails(){
	var cook = getCookie('cartCountPrice');
	var cartCountPriceList = [];
	if (isNull(cook)) {
		
	} else {
		cartCountPriceList = cookToArr(cook);
		var amount = 0;
		var total = 0;
		for(var i=0; i<cartCountPriceList.length; i++){
		  var skuId = cartCountPriceList[i][1];
		  var skuAmount = parseInt(cartCountPriceList[i][3]);
		  var skuPrice = parseFloat(cartCountPriceList[i][2]);
		  var id = "detail-"+skuId;
		   var el = $("#"+id);
		  if (el) {
			el.html(skuAmount);
		  }
		  total = parseFloat(total) + skuAmount * skuPrice;
		  total = total.toFixed(2);
		  if (skuAmount > 0) {
			amount ++;
		  }
		}
		$('#cart_num').html(amount);
	}
}
function zhifu(el){
	$('#hid_method').val($(el).attr('tig'));
	$('.pay_gouxuan').html('<img src="/images/yuan.jpg">');
	$(el).html('<img src="/images/gou.jpg">');
}

//时间和当前时间比较
function MyTimeDaNow(s){
	var nowDate = new Date();
	var hour = nowDate.getHours();
	var min = nowDate.getMinutes();
	var sec = nowDate.getSeconds();
	var listTime = s.split(":");
	var myhour = listTime[0];
	var myMin = listTime[1];
	var mySec = listTime[2];
	if(myhour>hour){
		return true;
	}if(myhour<=hour &&myMin>min){
		return true;
	}
	return false;
}

//品类
function category(){
	$.ajax({
		  type: "post", 
		  url : "/index", 
		  dataType: 'json',
		  data: {'tag':'pinlei'},
		  success: function(info){
			var res = info.msg;
			if(res == 'cusListNull'){
				alert('亲，该小区暂未开通哦，切换地址看看');
			}else if (res == 'presellNull'){
				alert('亲，该小区暂未开通哦，切换地址看看');
			}else{
				var shopid = res.id;
				location.href="/sku?shopid="+shopid;
			}
		  }
	});
}
//我的
function personalHandler(){
	$.ajax({
		  type: "post", 
		  url : "/index", 
		  dataType: 'json',
		  data: {'tag':'personal'},
		  success: function(info){
			var res = info.msg;
			if(res == 'notLogin'){
				var rurl ="/personal";
				location.href="/login?rurl="+rurl;
			}else{
				location.href="/personal";
			}
		  }
	});
}


function goBack () {
	if(history.length > 1) {
		history.back(-1); 
	}
}


function unloadHandler(){
	alert(111);
	return false;
}

function getWinHeight(){
	var winHeight='';
	if (window.innerHeight)
		winHeight = window.innerHeight;
	else if ((document.body) && (document.body.clientHeight))
		winHeight = document.body.clientHeight;
	return winHeight;
}

function changeDistributer(el){
	$('.disList').css('color','black');
	$(el).css('color','green');
	var id = $(el).attr('distributerId');	
	var sitename = $(el).attr('sitename');	
	var address = $(el).attr('address');	
	$.ajax({
		  type: "post", 
		  url : "/index/home", 
		  dataType: 'json',
		  data: {'id':id,'sitename':sitename,'address':address,'tag':'distributerClick'},
		  success: function(info){
			if(info.msg=='sessionSuccess'){
				$('#domain').html(sitename);
				$('#address').html(address);
				$('#wrapperHome').css('top',$('.topBar').css('height'));
				$('.Comman').css('top',$('.topBar').css('height'));
				$('#distributerList').hide();
				$('#masktg').hide();
			}
		  }
	});
}

function showDistributerList(){
	$('#distributerList').toggle();
	$('#masktg').toggle();
}

function hiddenFuCeng(){
	$("#distributerList").hide();
	$("#masktg").hide();
}

function ClickPersonalTabs(el){
	$('.personalTabs').css('border-bottom','0px');
	$(el).css('border-bottom','2px solid red');
	var tag = $(el).attr('tag');
	if(tag=='orderlist'){
		location.href="/order/list";
	}else{
		location.href="/voucher";
	}
}

function Trim(str,is_global){
        var result;
        result = str.replace(/(^\s+)|(\s+$)/g,"");
        if(is_global.toLowerCase()=="g")
        {
            result = result.replace(/\s/g,"");
        }
        return result;
	}
function creditConsume(el){
	var r = confirm("确定兑换吗？");
	if(true == r){
		var giftid = $(el).attr('giftId');
		var giftCredit = $(el).attr('giftCredit');
		var totalCredit = $('#totalCredit').text();
		if(isNull(giftid)||isNull(giftCredit))
			return;
		if(parseInt(totalCredit)<parseInt(giftCredit)){
			alert('亲，您的积分不足！');
			return;
		}
		$.ajax({
		  type: "post", 
		  url : "/credit", 
		  dataType: 'json',
		  data: {'giftid':giftid},
		  success: function(info){
			 var msg = info.msg;
			 if(msg=="error"){
				 alert('兑换失败！');
			 }
			 if(msg=='success'){
				 var res = info.res;
				 $('#totalCredit').html(res);
				 alert('兑换成功，请在我的现金券查收！');
			 }
		  }
		});
	}
}
function buyTopup(el){
	var tag = $(el).attr('tag');
	$('.gouBuy').html('<img src="/images/meigou.png"  class="gougou">');
	$('#gou'+tag).html('<img src="/images/yigou.png"  class="gougou">');
	$('#buyTopup').val(tag);
}

function zhifuHandler(el){
	var tag = $(el).attr('tag');
	if(tag=='weixin'){
		$('#weixin_zhifu').html('<img src="/images/yigou.png"  class="gougou">');
		$('#zhifubao_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
	}
	if(tag=='alipay'){
		$('#weixin_zhifu').html('<img src="/images/meigou.png"  class="gougou">');
		$('#zhifubao_zhifu').html('<img src="/images/yigou.png"  class="gougou">');
	}
	$('#payMethod').val(tag);
}
//快速充值
function submitRecharge(){
	$('#errMsg').html('');
	var tel = $('#tel').val();
	var roleId = $('#roleId').val();
	
	if(isNull(tel)){
		$('#errMsg').html('请输入手机号');
		return false;
	}
	if(tel.length!=11){
		$('#errMsg').html('请输入有效的手机号码！');
		return false;
	}
	var myreg = /^1[3|4|5|7|8][0-9]\d{4,8}$/;
	if(!myreg.test(tel))
	{
		$('#errMsg').html('请输入有效的手机号码！');
		return false;
	}
	if(isNull(roleId)){
		$('#errMsg').html('请选择充值金额');
		return false;
	}
	$('#rechargeBtn').attr("disabled","true");
	rechargeCallWXPay(tel,roleId);
}

function rechargeCallWXPay(tel,roleId){
	$.ajax({
		  type: "post", 
		  url : "/personal/recharge", 
		  dataType: 'json',
		  data: {'tel':tel,'roleId':roleId},
		  complete: function (info) {
			 $('#rechargeBtn').attr("disabled","false");
		  },			  
		  success: function(info){
			var msg = info.msg;
			if(!isNull(msg) && msg=='needLogin'){
				location.href="/personal/validate?tel="+tel+"&roleId="+roleId;
			}else if(msg=='errorToDetails' ||msg =='dataError'){
				alert('支付失败，订单已支付或订单已超过支付期限');
				location.href = '/personal/topupdetail';
				return false;
			}else if(msg=='success'){
				var wxparams = info.wxparams;
				var transactionId = info.transactionId;
				var topupid = info.topupid;
			
				if (typeof WeixinJSBridge == "undefined"){
					if( document.addEventListener ){
						document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
					}else if (document.attachEvent){
						document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
						document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
					}
				}else{
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest',
						wxparams,
						function(res){
							WeixinJSBridge.log(res.err_msg);
							//alert(res.err_code+res.err_desc+res.err_msg);
							if(res.err_msg=="get_brand_wcpay_request:fail"){
								alert('支付失败，订单已支付或订单已超过支付期限');
								location.href='/personal/topupdetail';
							}if (res.err_msg=="get_brand_wcpay_request:cancel"){
								alert('支付取消');
								location.href='/personal/topupdetail';
							}if(res.err_msg=="get_brand_wcpay_request:ok"){
								alert('支付成功');
								location.href="/personal/wxquery?trade_no="+transactionId+"&topupid="+topupid+"&type=kk";
							}
						}
					);
				}
			}else{
				location.href = '/error';
			}
		  },
		  error:function(){
			   alert('支付失败');
			  location.href='/personal/topupdetail';
		  }
	});
	
}
//余额充值
function confirmTopup(){
	if($('#agreeProtocol').val()==1){
		var roleid = $('#buyTopup').val();
		var payMethod = $('#payMethod').val();
		$('#topupPay').attr("disabled","true");
		if(payMethod=='weixin'){
			topupCallWXPay(roleid);
		}else if(payMethod=='alipay'){
			// topupCallAliPay(roleid);
		}
	}else{
		alert('请同意鲜店余额协议');
	}
}
//alipay
function topupCallAliPay(roleid){
	$.ajax({
		  type: "post", 
		  url : "/personal/topup", 
		  dataType: 'json',
		  data: {'roleid':roleid,'tag':'alipay'},
		  complete: function () {
            $('#topupPay').attr("disabled","false");
		  },			  
		  success: function(info){
			var transactionId = info.transactionId;
			var inserttime = info.inserttime;
			if(transactionId==0){
				alert('支付失败，订单已支付或订单已超过支付期限');
				// location.href="/order/status?oid="+oid;
			}else{
				alert('支付成功');
				location.href = "/personal/zfbpay?roleid="+roleid+"&transactionId="+transactionId+"&inserttime="+inserttime;
			}
		  }
	});
}
//wxpay
function topupCallWXPay(roleid){
	$.ajax({
		  type: "post", 
		  url : "/personal/topup", 
		  dataType: 'json',
		  data: {'roleid':roleid,'tag':'weixin'},
		  complete: function (info) {
			 $('#topupPay').attr("disabled","false");
		  },			  
		  success: function(info){
			var msg = info.msg;
			if(msg=='errorToDetails'){
				alert('支付失败，订单已支付或订单已超过支付期限');
				location.href = '/personal/topupdetail';
			}else if(msg=='success'){
				var wxparams = info.wxparams;
				var transactionId = info.transactionId;
				var topupid = info.topupid;
			
				if (typeof WeixinJSBridge == "undefined"){
					if( document.addEventListener ){
						document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
					}else if (document.attachEvent){
						document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
						document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
					}
				}else{
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest',
						wxparams,
						function(res){
							WeixinJSBridge.log(res.err_msg);
							//alert(res.err_code+res.err_desc+res.err_msg);
							if(res.err_msg=="get_brand_wcpay_request:fail"){
								alert('支付失败，订单已支付或订单已超过支付期限');
								location.href='/personal/topupdetail';
							}if (res.err_msg=="get_brand_wcpay_request:cancel"){
								alert('支付取消');
								location.href='/personal/topupdetail';
							}if(res.err_msg=="get_brand_wcpay_request:ok"){
								alert('支付成功');
								location.href="/personal/wxquery?trade_no="+transactionId+"&topupid="+topupid+"&type=kk";
							}
						}
					);
				}
			}else{
				location.href = '/error';
			}
			
		  }
	});
	
}
function agreeProtocol(){
		var agreeProtocolVal = $('#agreeProtocol').val();
		if(agreeProtocolVal==1){
			$('#agreeGou').attr('src','/images/meigou.png');
			$('#agreeProtocol').val(0);			
		}
		if(agreeProtocolVal==0){
			$('#agreeGou').attr('src','/images/yigou.png');
			$('#agreeProtocol').val(1);
		}
}
	function confirmHelper(){
		$('.error_msg').html('');
		var account = $('#account').val();
		var sex = $('#sex').val();
		var idCartNum = $('#idCartNum').val();
		var tel = $('#tel').val();
		var partnerMethod = $('#partnerMethod').val();
		var money = $('#money').val();
		var place = $('#place').val();
		
		if(isNull(account) || isNull(tel) || place==0){
			$('.error_msg').html('红色星号标注为必填选项');
			return false;
		}
		if(tel.length!=11){
			$('.error_msg').html('请输入有效的手机号码！');
			return false;
		}
		var myreg = /^1[3|4|5|7|8][0-9]\d{4,8}$/;
		if(!myreg.test(tel))
		{
			$('.error_msg').html('请输入有效的手机号码！');
			return false;
		}
		if(!isNull(money)&&isNaN(money)){
		    $('.error_msg').html('请输入有效的金额！');
			return false;
		}
		$('#partnerBtn').attr('disabled','true');
		$.ajax({
		  type: "post", 
		  url : "/partner", 
		  dataType:'json',
		  data:{'account':account,'sex':sex,'idCartNum':idCartNum,'tel':tel,'partnerMethod':partnerMethod,'money':money,'place':place},
		  success: function(info){
			  $('#partnerBtn').attr('disabled','false');
			  var msg  = info.msg;
			  if(!isNull(msg) && msg=='success'){
				  alert('加盟信息添加成功，工作人员会及时向您联系');
				  location.href = location.href;
			  }else{
				  alert('加盟信息添加失败');
			  }
		  },
		  error:function(){
			   alert('加盟信息添加失败!');
		  },
		  complete:function(){
			   $('#partnerBtn').attr('disabled','false');
		  }
		});
	}
	
	
	
	function actionHelper(el){
		var actionStr = $(el).attr('actionStr');
		$.ajax({
		  type: "post", 
		  url : "/index/click", 
		  dataType:'json',
		  data:{'actionStr':actionStr},
		  success: function(info){
			  var msg = info.msg;
			  if(msg=='success'){
				  var actionId = info.actionId;
				  var paras = info.parameter;
				  if(actionId=='1' || actionId=='2'){
					  var url = paras.url;
					  setCookie('tab','category');
					  location.href='/';
				  }
				  if(actionId=='3'){
					  var shopProductId = info.shopProductId;
					  if(!isNull(shopProductId)){
						location.href="/sku/details?id="+shopProductId;
					  }else{
						  location.href="/";
					  }
				  }
				  if(actionId=='4'){
					  var brandId = paras.brandId;
					  $(el).attr('hotid',brandId);
					  loadCategoryPage(el);
				  }
				  if(actionId=='5'){
					  var presaleId = paras.presaleId;
					  location.href="/presalesku/details?id="+presaleId;
				  }
			  }
		  },
		  error : function(){
			  
		  }
		});
	}
	
function toAddress(oid){
	location.href="/address/presale?oid="+oid;
}